<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { updateOrderAmount } from '@/api/order/admin'

const props = defineProps<{
  visible: boolean
  orderNo: string
  currentAmount: number
  remark?: string
}>()

const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}>()

const dialogVisible = ref(false)

const form = reactive({
  orderNo: '',
  payAmount: 0,
  remark: ''
})

const loading = ref(false)

// 监听visible变化
watch(
  () => props.visible,
  (val) => {
    dialogVisible.value = val
    if (val) {
      // 初始化表单数据
      form.orderNo = props.orderNo
      form.payAmount = props.currentAmount
      form.remark = props.remark || ''
    }
  },
  { immediate: true }
)

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
  emit('update:visible', false)
}

// 提交表单
const handleSubmit = async () => {
  if (!form.orderNo) {
    ElMessage.warning('订单号不能为空')
    return
  }

  if (form.payAmount === undefined || form.payAmount < 0) {
    ElMessage.warning('请输入有效的订单金额')
    return
  }

  try {
    loading.value = true
    const res: any = await updateOrderAmount({
      orderNo: form.orderNo,
      payAmount: form.payAmount,
      remark: form.remark
    })

    if (res.code === 200) {
      ElMessage.success('订单金额更新成功')
      emit('success')
      // 清空表单数据
      form.orderNo = ''
      form.payAmount = 0
      form.remark = ''
      handleClose()
    } else {
      ElMessage.error(res.message || '更新失败')
    }
  } catch (error: any) {
    ElMessage.error(error.message || '更新订单金额时发生错误')
    console.error(error)
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <el-dialog v-model="dialogVisible" title="修改订单金额" width="500px" :before-close="handleClose">
    <el-form :model="form" label-width="80px" label-position="left">
      <el-form-item label="订单号">
        <el-input v-model="form.orderNo" disabled />
      </el-form-item>

      <el-form-item label="订单金额" prop="payAmount">
        <el-input-number
          v-model="form.payAmount"
          placeholder="请输入订单金额"
          style="width: 100%"
          :min="0"
          :precision="2"
          controls-position="right"
        />
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" :rows="3" />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
